import { useState, useEffect, useRef } from "react"
import { Haptics } from "@capacitor/haptics"
import { Motion } from "@capacitor/motion"
import { questions, heartStyles } from "./config"
import "./App.css"
import { Howl } from "howler"
import mp3 from "./money.mp3"

function App() {
  const [currentCard, setCurrentCard] = useState(null)
  const [currentHeart, setCurrentHeart] = useState("💝")
  const [showGuide, setShowGuide] = useState(true)

  const player = useRef(null)
  useEffect(() => {
    player.current = new Howl({
      src: [mp3],
      volume: 1,
    })
    return () => {
      player.current.unload()
      player.current = null
    }
  }, [])

  const handleShake = (() => {
    let timer = null
    return () => {
      if (timer) return
      setShowGuide(false)
      const randomIndex = Math.floor(Math.random() * questions.length)
      const randomHeartIndex = Math.floor(Math.random() * heartStyles.length)
      setCurrentCard(questions[randomIndex])
      setCurrentHeart(heartStyles[randomHeartIndex])
      Haptics.vibrate(500)
      player.current && player.current.play()
      timer = setTimeout(() => {
        timer = null
      }, 500)
    }
  })()

  useEffect(() => {
    let lastUpdate = 0
    const threshold = 15
    const cooldown = 1000

    const handleMotion = async ({ acceleration }) => {
      const now = Date.now()
      if (now - lastUpdate < cooldown) return

      const { x, y, z } = acceleration
      const accelerationMagnitude = Math.sqrt(x * x + y * y + z * z)

      if (accelerationMagnitude > threshold) {
        lastUpdate = now
        handleShake()
      }
    }

    const setupShakeDetection = async () => {
      try {
        await Motion.addListener("accel", handleMotion)
      } catch (error) {
        console.error("Error setting up motion listener:", error)
      }
    }

    setupShakeDetection()

    return () => {
      Motion.removeAllListeners()
    }
  }, [])

  return (
    <div className="app">
      <div className="container">
        <div className="card-display left">
          {currentCard && (
            <div className="card" key={currentCard}>
              {currentHeart} {currentCard}
            </div>
          )}
        </div>
        <div className="pencil-holder" onClick={handleShake}>
          <span className="hand-icon animate-float">👋</span>
          {showGuide && <div className="guide-text"> 急急如律令!💫</div>}
          <div className="cards-stack">
            {[...Array(5)].map((_, index) => (
              <div key={index} className="stacked-card" />
            ))}
          </div>
          <div className="decorative-icons">
            <span className="icon-float">💖</span>
            <span className="icon-float delay-1">⭐</span>
            <span className="icon-float delay-2">💝</span>
            <span className="icon-float delay-3">✨</span>
          </div>
        </div>
      </div>
    </div>
  )
}

export default App
